package net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Server extends Thread{
	
	private int port ;
	private InetAddress address;
	public Server(int port, InetAddress address) {
		super();
		this.port = port;
		this.address = address;
	}
	
	@Override
	public void run() {
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(port, address);
			// 循环读
			while(true) {
				byte[] bytes = new byte[1024];
				DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
				socket.receive(packet);
				
				// 输出数据
				String content = new String(bytes, packet.getOffset(), packet.getLength());
				System.out.println("接收到的数据是：" + content);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(socket != null) {
				socket.close();
			}
		}
		
	}
}
